<?php

namespace catchAdmin\model;

class Notice extends ModelApp
{

    public $name = 'notice';


    protected $append = [
        'create_at_show',
        'notice_type_name',
        'read_time_show',
        'read_is',
    ];


    ############################ 关系 start ##########################

    public function wechatUser()
    {
        return $this
            ->hasOne(WechatUser::class, 'id', 'wechat_user_id')
            ->bind([
                'wechat_user_name' => 'nickname',
            ]);
    }


    ############################ 关系 end ##########################
    ############################ Attr start ##########################

    /**
     * create_at_show
     */
    public function getCreateAtShowAttr()
    {
        return formatRelativeTime($this->getOrigin('created_at'));
    }


    /**
     * notice_type_name_list
     */
    public function getNoticeTypeNameList()
    {
        return [
            1 => '公司认证',
            2 => '提现审核',
            3 => '需求审核',
            4 => '个人认证',
            5 => '招聘',
            6 => '留言',
        ];
    }


    /**
     * notice_type_name
     */
    public function getNoticeTypeNameAttr()
    {
        return $this->getNoticeTypeNameList()[$this->getOrigin('notice_type')] ?? '';
    }


    /**
     * read_time_show
     */
    public function getReadTimeShowAttr()
    {
        if (empty($this->getOrigin('read_time'))) {
            return '';
        }

        return date('Y-m-d H:i:s', $this->getOrigin('read_time'));
    }


    /**
     * read_is
     */
    public function getReadIsAttr()
    {
        if (empty($this->getOrigin('read_time'))) {
            return 0;
        }

        return 1;
    }


    ############################ Attr end ##########################
    ############################ search start ##########################

    public function searchContentAttr($query, $value, $data)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }


    public function searchNoticeTypeAttr($query, $value, $data)
    {
        $query->where('notice_type', $value);
    }


    public function searchTitleAttr($query, $value, $data)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }


    /**
     * wechat_user_name
     */
    public function searchWechatUserNameAttr($query, $value, $data)
    {
        $query
            ->join('wechat_user', 'wechat_user.id = notice.wechat_user_id', 'INNER')
            ->where('wechat_user.nickname', 'like', '%' . $value . '%');
    }

    ############################ search end ##########################

}
